package com.yida.common.core.utils.ip;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;

import com.alibaba.fastjson2.JSONObject;
import com.yida.common.core.utils.StringUtils;

import cn.hutool.http.HttpUtil;

/**
 * 获取IP方法
 * 
 * @author yida
 */
public class IpUtils {

    private static final Logger log = LoggerFactory.getLogger(IpUtils.class);

    /**
     * 获取客户端IP
     * 
     * @param request 请求对象
     * @return IP地址
     */
    public static String getIpAddr(HttpServletRequest request) {
        if (request == null) {
            return "unknown";
        }
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 兼容k8s集群获取ip
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : getMultistageReverseProxyIp(ip);
    }

    /**
     * 检查是否为内部IP地址
     * 
     * @param ip IP地址
     * @return 结果
     */
    public static boolean internalIp(String ip) {
        byte[] addr = textToNumericFormatV4(ip);
        return internalIp(addr) || "127.0.0.1".equals(ip);
    }

    /**
     * 检查是否为内部IP地址
     * 
     * @param addr byte地址
     * @return 结果
     */
    private static boolean internalIp(byte[] addr) {
        if (StringUtils.isNull(addr) || addr.length < 2) {
            return true;
        }
        final byte b0 = addr[0];
        final byte b1 = addr[1];
        // 10.x.x.x/8
        final byte SECTION_1 = 0x0A;
        // 172.16.x.x/12
        final byte SECTION_2 = (byte)0xAC;
        final byte SECTION_3 = (byte)0x10;
        final byte SECTION_4 = (byte)0x1F;
        // 192.168.x.x/16
        final byte SECTION_5 = (byte)0xC0;
        final byte SECTION_6 = (byte)0xA8;
        switch (b0) {
            case SECTION_1:
                return true;
            case SECTION_2:
                if (b1 >= SECTION_3 && b1 <= SECTION_4) {
                    return true;
                }
            case SECTION_5:
                switch (b1) {
                    case SECTION_6:
                        return true;
                }
            default:
                return false;
        }
    }

    /**
     * 将IPv4地址转换成字节
     * 
     * @param text IPv4地址
     * @return byte 字节
     */
    public static byte[] textToNumericFormatV4(String text) {
        if (text.length() == 0) {
            return null;
        }

        byte[] bytes = new byte[4];
        String[] elements = text.split("\\.", -1);
        try {
            long l;
            int i;
            switch (elements.length) {
                case 1:
                    l = Long.parseLong(elements[0]);
                    if ((l < 0L) || (l > 4294967295L)) {
                        return null;
                    }
                    bytes[0] = (byte)(int)(l >> 24 & 0xFF);
                    bytes[1] = (byte)(int)((l & 0xFFFFFF) >> 16 & 0xFF);
                    bytes[2] = (byte)(int)((l & 0xFFFF) >> 8 & 0xFF);
                    bytes[3] = (byte)(int)(l & 0xFF);
                    break;
                case 2:
                    l = Integer.parseInt(elements[0]);
                    if ((l < 0L) || (l > 255L)) {
                        return null;
                    }
                    bytes[0] = (byte)(int)(l & 0xFF);
                    l = Integer.parseInt(elements[1]);
                    if ((l < 0L) || (l > 16777215L)) {
                        return null;
                    }
                    bytes[1] = (byte)(int)(l >> 16 & 0xFF);
                    bytes[2] = (byte)(int)((l & 0xFFFF) >> 8 & 0xFF);
                    bytes[3] = (byte)(int)(l & 0xFF);
                    break;
                case 3:
                    for (i = 0; i < 2; ++i) {
                        l = Integer.parseInt(elements[i]);
                        if ((l < 0L) || (l > 255L)) {
                            return null;
                        }
                        bytes[i] = (byte)(int)(l & 0xFF);
                    }
                    l = Integer.parseInt(elements[2]);
                    if ((l < 0L) || (l > 65535L)) {
                        return null;
                    }
                    bytes[2] = (byte)(int)(l >> 8 & 0xFF);
                    bytes[3] = (byte)(int)(l & 0xFF);
                    break;
                case 4:
                    for (i = 0; i < 4; ++i) {
                        l = Integer.parseInt(elements[i]);
                        if ((l < 0L) || (l > 255L)) {
                            return null;
                        }
                        bytes[i] = (byte)(int)(l & 0xFF);
                    }
                    break;
                default:
                    return null;
            }
        } catch (NumberFormatException e) {
            return null;
        }
        return bytes;
    }

    /**
     * 获取IP地址
     * 
     * @return 本地IP地址
     */
    public static String getHostIp() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
        }
        return "127.0.0.1";
    }

    /**
     * 获取主机名
     * 
     * @return 本地主机名
     */
    public static String getHostName() {
        try {
            return InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
        }
        return "未知";
    }

    /**
     * 从多级反向代理中获得第一个非unknown IP地址
     *
     * @param ip 获得的IP地址
     * @return 第一个非unknown IP地址
     */
    public static String getMultistageReverseProxyIp(String ip) {
        // 多级反向代理检测
        if (ip != null && ip.indexOf(",") > 0) {
            final String[] ips = ip.trim().split(",");
            for (String subIp : ips) {
                if (false == isUnknown(subIp)) {
                    ip = subIp;
                    break;
                }
            }
        }
        return ip;
    }

    /**
     * 检测给定字符串是否为未知，多用于检测HTTP请求相关
     *
     * @param checkString 被检测的字符串
     * @return 是否未知
     */
    public static boolean isUnknown(String checkString) {
        return StringUtils.isBlank(checkString) || "unknown".equalsIgnoreCase(checkString);
    }

    // ----------------------新增功能保留区---------------------------------------------------------

    // 多次反向代理后会有多个ip值 的分割符
    private final static String IP_UTILS_FLAG = ",";
    // 本地 IP
    private final static String LOCALHOST_IP = "0:0:0:0:0:0:0:1";
    private final static String LOCALHOST_IP1 = "127.0.0.1";

    public static String getIpAddr(ServerHttpRequest request) {
        // 根据 HttpHeaders 获取 请求 IP地址
        String ip = request.getHeaders().getFirst("X-Forwarded-For");
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst("x-forwarded-for");
            if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
                // 多次反向代理后会有多个ip值，第一个ip才是真实ip
                if (ip.contains(IP_UTILS_FLAG)) {
                    ip = ip.split(IP_UTILS_FLAG)[0];
                }
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst("X-Real-IP");
        }
        // 兼容k8s集群获取ip
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddress().getAddress().getHostAddress();
            if (LOCALHOST_IP1.equalsIgnoreCase(ip) || LOCALHOST_IP.equalsIgnoreCase(ip)) {
                // 根据网卡取本机配置的IP
                InetAddress iNet = null;
                try {
                    iNet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    log.error("getClientIp error: ", e);
                }
                ip = iNet.getHostAddress();
            }
        }
        return ip;
    }
    // ----------------------新增功能保留区---------------------------------------------------------

    /**
     * description 地址库查询
     *
     * @param ip 地址
     * @return java.lang.String
     * @version 1.0
     */
    // public static String getRealAddress(String ip) {
    // if (internalIp(ip)) {
    // return "本地网络";
    // }
    // String result = "未知网络";
    // try {
    // // 加载地址库
    // ClassPathResource resource = new ClassPathResource("GeoLite2-City.mmdb");
    // DatabaseReader reader = new DatabaseReader.Builder(resource.getInputStream()).build();
    // InetAddress inetAddress = InetAddress.getByName(ip);
    // CityResponse response = reader.city(inetAddress);
    // // 获取所在国家
    // String country = response.getCountry().getNames().get("ja");
    // // 1 由库内获取IP信息
    // if (response.getSubdivisions().size() > 0) {
    // // 获取所在省份
    // String province = response.getSubdivisions().get(0).getNames().get("zh-CN");
    // // 获取所在城市
    // String city = response.getCity().getNames().get("zh-CN");
    // city = city == null ? "" : city;
    // result = country + province + city;
    // }
    // // else {
    // // // 库内获取不到的IP，访问ali的地域查询
    // // result = getAlibaba(ip);
    // // }
    // } catch (Exception e) {
    // log.error("未知网络", e);
    // return "未知网络";
    // }
    // return result;
    // }

    public static String getRealAddress(String ip) {
        if (internalIp(ip)) {
            return "本地网络";
        }
        String result = "未知网络";
        try {
            result = getRealAddress(ip, 0);
        } catch (Exception e) {
            log.error("未知网络", e);
            return "未知网络";
        }
        return result;
    }

    private static String getRealAddress(String ip, int type) {
        String result = "未知网络";
        switch (type) {
            case 0:
                result = Ip2region2Utils.getRealAddress(ip);
                break;
            case 1:
                result = getIpByBaiDuAPI(ip);
                break;
            default:
                result = "未知网络";
        }
        return result;
    }

    /**
     * description ali地域查询 这个已经废了
     *
     * @param ip ip地址
     * @return java.lang.String
     * @version 1.0
     */
    public static String getAlibaba(String ip) {
        // Map map = new HashMap(2);
        Map<String, Object> map = new HashMap<>(2);
        map.put("ip", ip);
        map.put("accessKey", "alibaba-inc");
        String result = HttpUtil.post("http://ip.taobao.com/outGetIpInfo", map);
        JSONObject json = JSONObject.parseObject(result);
        // Map<String, String> valueMap = JSONObject.parseObject(result, Map.class);

        // 请求成功，解析响应数据
        if ("query success".equals(json.get("msg"))) {
            // Map<String, String> dataMap = (Map<String, String>)valueMap.get("data");
            JSONObject data = json.getJSONObject("data");
            if (data.isEmpty()) {
                return "未知网络";
            }
            String country = data.getString("country");
            String region = data.getString("region");
            String city = data.getString("city");
            return country + region + city;
        }
        return "";
    }

    /**
     * 百度IP
     * 
     * @param ip
     * @return
     */
    public static String getIpByBaiDuAPI(String ip) {
        String result = HttpUtil.get("https://opendata.baidu.com/api.php?query=" + ip + "&resource_id=6006&co=&oe=utf8");
        JSONObject json = JSONObject.parseObject(result);
        // Map<String, String> valueMap = JSONObject.parseObject(result, Map.class);

        // 请求成功，解析响应数据
        if ("0".equals(json.get("status"))) {
            // Map<String, String> dataMap = (Map<String, String>)valueMap.get("data");
            JSONObject data = json.getJSONArray("data").getJSONObject(0);
            if (data.isEmpty()) {
                return "未知网络";
            }

            return data.getString("location");
        }
        return "";
    }
    
    /**
     * 获取服务器IP数据
     * @return
     */
    public static List<String> getLocalIPAddress(){
    	List<String> ipList = new ArrayList<String>();
    	try {
            // 获取本机的所有网络接口
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface networkInterface = interfaces.nextElement();
                // 确保网络接口已启用
                if (networkInterface.isUp()) {
                    // 确保不是虚拟网络接口
                    if (!networkInterface.isVirtual()) {
                        // 遍历每个接口地址
                        Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                        while (addresses.hasMoreElements()) {
                            InetAddress inetAddress = addresses.nextElement();
                            // 确保是IPv4地址，并且不是环回地址
                            if (!inetAddress.isLoopbackAddress() && inetAddress.getAddress().length == 4) {
                                //System.out.println("Local IP Address: " + inetAddress.getHostAddress());
                            	ipList.add(inetAddress.getHostAddress());
                            }
                        }
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
    	return ipList;
    }

    public static void main(String[] args) {
        // System.out.println(IpUtils.getRealAddress("110.88.161.105"));
        // for (int i = 0; i < 10; i++) {
        // Long s = System.currentTimeMillis();
        // System.out.println(IpUtils.getIpByBaiDuAPI("110.88.161.105"));
        // Long e = System.currentTimeMillis();
        // System.out.println((s - e) / 1000);
        // }

        for (int i = 0; i < 10; i++) {
            System.out.println(IpUtils.getRealAddress("110.88.161.105"));
        }

    }

}